package com.tanhua.sso.controller;

import com.tanhua.sso.service.SmsService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("user")
@Slf4j
public class SmsController {
    @Autowired
    private SmsService smsService;

    //前端传递的数据格式为application/json,用map进行封装成k、v
    @PostMapping("login")
    public ResponseEntity<ErrorResult> sendCheckCode(@RequestBody Map<String,String> param){
        ErrorResult errorResult=null;
        String phone=param.get("phone");
        try {
            //调用smsService.sendCheckCode方法,获取ErrorResult对象
            errorResult=this.smsService.sendCheckCode(phone);
            //根据返回的结果，如果为空，那么就没有出现"上一次发送的验证码还未失效";"发送短信验证码失败!";即短信成功发送了
            if(null==errorResult){
                return ResponseEntity.ok(null);
            }
        } catch (Exception e) {
            log.error("发送短信验证码失败~ phone="+phone,e);
            errorResult=ErrorResult.builder().errCode("000002").errMessage("短信验证码发送失败！").build();
        }
        //返回500服务器内部错误,表示验证码发送失败
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }
}
